package com.wds.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wds.domain.JsonResult;
import com.wds.domain.type.AppHttpCodeEnum;
import com.wds.common.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-10-27 18:11
 * 认证失败异常处理
 */
@Component

public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ObjectMapper mapper = new ObjectMapper();
        JsonResult<Object> result = null;

        if (authException instanceof InsufficientAuthenticationException) {
            result = JsonResult.fail(401, "登录状态失效，请重新登录");
        } else if (authException instanceof BadCredentialsException) {
            result = JsonResult.fail(AppHttpCodeEnum.LOGIN_ERROR);
        } else {
            result = JsonResult.fail(505, "认证失败");
        }

        WebUtils.renderString(response, mapper.writeValueAsString(result));
    }
}
